#!/bin/bash

# 检查SOP分支类型
SOP_MATCH=$(echo ${GIT_BRANCH} | grep -c "sop[0-9]*$" | head -n 1)
SOP_MATCH_S=$(echo ${GIT_BRANCH} | sed -n "s/.*s\.\([0-9]\+\).*/sop\1/p")

# 获取SOP名称
SOP_NAME=""
if [ $SOP_MATCH -ne 0 ]; then
    echo "匹配到有 sop 分支"
    SOP_NAME=$(echo "${GIT_BRANCH}" | grep -Eo "sop[0-9]*$" | head -n 1)
elif [ -n "$SOP_MATCH_S" ]; then
    echo "匹配到有 S. 分支"
    SOP_NAME=$SOP_MATCH_S
fi

# 设置应用名称
APP_NAME=${appName:-${APPLICATION_VERSION}}
echo "应用名称: ${APP_NAME}"

# 获取APK文件路径
if [ -n "$apkSpecificPath" ]; then
    APK_FILE_PATH=$(find . -name "*.apk" | grep "${apkSpecificPath}" | head -n 1)
else
    APK_FILE_PATH=$(find . -name "*.apk" | grep "build/outputs/" | head -n 1)
fi
echo "APK路径: ${APK_FILE_PATH}"

# 设置APK在warehouse中的名称
APK_WAREHOUSE_NAME="${APP_NAME}.apk"

# 构建warehouse路径
BASE_PATH="%2FXHZL-private-repo%2FappWarehouse-${PROJECT_KEY}"
if [ -n "$SOP_NAME" ]; then
    echo "上传到SOP目录"
    SOP_PREFIX="${BASE_PATH}%2F${SOP_NAME}"
else
    echo "上传到主线目录"
    SOP_PREFIX="${BASE_PATH}"
fi

if [ -n "$apkRemotePath" ]; then
    APP_WAREHOUSE_PATH="${SOP_PREFIX}%2Fgxatek%2F${apkRemotePath}%2F${APP_NAME}"
else
    APP_WAREHOUSE_PATH="${SOP_PREFIX}%2Fgxatek%2F${APP_NAME}"
fi
